import baseUrl from './url.js'
import Vue from 'vue'

var request = function(options) {
     try {
       // 获取放入缓存的字段token
       const token = uni.getStorageSync('token');
	   const placeId = uni.getStorageSync('placeId');
       if (token) { // 如果存在token 配置请求头
         options.header = {
           'Authorization' : 'Bearer ' + token,
		   'Content-Type' : 'application/json; charset=UTF-8',
		   'x-tenant-header': placeId
         };
        }else if (options.url.indexOf('toLogin') > 0 || options.url.indexOf('loginByOfficialAccounts') > 0) {
			options.header = {
			  'Content-Type' : 'application/json; charset=UTF-8'
			};
		}else{	// 不存在token 跳转至登录
            uni.navigateTo({
                url: '/pages/login/index' 
            });
            return;
        }
     } catch (err) {
      console.log(err)
    }
    // 这里对response进行处理，
    // 401表示登录状态过期，需重新登录
	options.complete = (response) => {
		if (response.statusCode == 401) {
			uni.navigateTo({
			   url: '/pages/login/index' 
			});
			return;
		}
	}
    return uni.request(options);
  }
  var myrequest = {};
  myrequest.post = function(url, data) {
	  return new Promise((resolve, reject) => {
		 request({
			 url: baseUrl + url,
			 method: 'post',
			 data: data || {},
			 success: (res) => {
				 var {data} = res;
				 if (data.success) {
					 resolve(data)
				 } else {
					 reject(data)
				 }
			 }
		 })
	  })
  }
  myrequest.get = function(url, data) {
  	  return new Promise((resolve, reject) => {
  		 request({
  			 url: baseUrl + url,
  			 method: 'get',
  			 data: data || {},
  			 success: (res) => {
  				 var { data } = res;
				 if (data.success) {
					 resolve(data)
				 } else {
					 reject(data)
				 }
  			 }
  		 })
  	  })
  }
  uni.sniper = myrequest;